using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using AopAlliance.Intercept;
using Sedna.API.Session;
using Sedna.API.Support;
using Sedna.Core;
using Sedna.Core.Security;
using Sedna.DAO;

namespace Sedna.API.Security
{
    public class ServerAuthInterceptor: IMethodInterceptor
    {
        private ISessionAware sessionAware;
        private IBaseDAO baseDAO;

        public ISessionManager SessionManager
        {
            set { sessionAware = value; }
        }

        public IBaseDAO BaseDAO
        {
            set { baseDAO = value; }
        }

        public object Invoke(IMethodInvocation invocation)
        {
            try
            {                
                sessionAware.CurrentSessionKey = (IToken) invocation.Arguments[0];
             
                SednaWorkPrincipal principal = Thread.CurrentPrincipal as SednaWorkPrincipal;
                if (principal != null)
                {
                    baseDAO.AttachToSession(principal.User);
                }
            } 
            catch (InvalidCastException)
            {
                throw new SednaException(SednaExceptionCodes.NotAuthenticated, "You are not logged in!");
            }
            
            return invocation.Proceed();
        }
        
    }
}

